package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传图片
     * @param multipartFile
     * @return
     */
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 效验参数
        if (multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 是否登录
        WmUser user = WmThreadLocal.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 上传图片到mini
        // 获取文件名
        String originalFilename = multipartFile.getOriginalFilename();
        // 文件后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = (UUID.randomUUID().toString().replace("-", "")) + substring;
        // 检测文件是否违法


        // 上传的url路径
        String path = null;
        try {
            path = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
            log.info("上传图片到minio，url为:{}", path);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件失败");
        }
        // 保存数据并修改数据库
        WmMaterial wmMaterial = WmMaterial.builder()
                .userId(user.getId())
                .url(path)
                .isCollection((short) 0)   // 是否收藏，默认不收藏0
                .type((short) 0)     // 素材类型，默认为图片0
                .createdTime(new Date())
                .build();
        this.save(wmMaterial);
        // 返回数据
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 列表查询
     * @param wmMaterialDto
     * @return
     */
    public ResponseResult findList(WmMaterialDto wmMaterialDto) {
        // 效验参数
        if (wmMaterialDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmMaterialDto.checkParam();
        // 是否登录
        WmUser user = WmThreadLocal.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构造分页条件
        IPage page = new Page(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        // 构造查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        // 当前登录用户
        wrapper.eq(WmMaterial :: getUserId, user.getId());
        // 判断是否收藏
        if (wmMaterialDto.getIsCollection() == 1){
            wrapper.eq(WmMaterial :: getIsCollection, wmMaterialDto.getIsCollection());
        }
        // 上传时间降序排序
        wrapper.orderByDesc(WmMaterial :: getCreatedTime);
        // 分页查询
        this.page(page, wrapper);
        // 封装返回
        PageResponseResult pageResponseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }
}
